<template>
  <el-dialog v-model="dialogVisible" :title="(props.id ? '更新' : '新增') + props.title" :width="props.width" :before-close="clickCancel">
    <slot name="body"> </slot>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm"> {{ props.id ? '更新' : '新增' }} </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: {
    type: Number
  },
  title: {
    type: String
  },
  width: {
    type: String,
    default: '45%'
  }
})
//['update', 'insert', 'update:visible']
const emit = defineEmits<{
  (e: 'save', waitPromise: (success: boolean) => void): void
  (e: 'query', id: typeof props.id): void
  (e: 'update:visible', value: boolean): void //无需在父组件注册update:visible
  (e: 'cancel'): void
}>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})
// 监听取消
watch(
  () => props.visible,
  (visible) => {
    if (!visible) emit('cancel')
  }
)
function cancel() {
  dialogVisible.value = false
}

// 监听id改变
watch(
  () => props.visible,
  async (newVisible, oldVisible) => {
    if (newVisible && props.id != null) emit('query', props.id)
  }
)
// 点击确认更新|新增操作
function confirm() {
  emit('save', (success) => {
    ElMessage({
      showClose: true,
      message: (props.id ? '更新' : '添加') + (success ? '成功' : '失败'),
      type: success ? 'success' : 'error'
    })
    if (success) clickCancel()
  })
}
// 点击取消操作
function clickCancel() {
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.el-dialog {
  border-radius: 10px !important;

  .el-dialog__header {
    line-height: 17px;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 700;
    }
  }

  .el-dialog__footer {
    .el-radio {
      margin-top: 20px;
      padding: 14px 22px;
      width: 100%;
      border: 1px solid #e5e4e4;
      border-radius: 4px;
      background: #fbfbfa;
    }

    .el-button--primary {
      border: none;
      background-color: #ffc200;
    }
  }
}
</style>
